package com.htl.exampro.base.model;

import com.htl.exampro.base.exception.CommonError;
import com.htl.exampro.base.exception.ExamProException;
import lombok.Data;
import lombok.ToString;

import java.util.List;

/**
 * 通用结果类型
 */

@Data
@ToString
public class ServerResponse<T> {

    /**
     * 响应编码,1为正常/-1失败
     */
    private int code;

    /**
     * 响应提示信息
     */
    private String message;

    /**
     * 响应内容
     */
    private T result;


    public ServerResponse() {
        this(1, "success");
    }

    public ServerResponse(int code, String message) {
        this(1, null, message);
    }

    public ServerResponse(int code, T result, String message) {
        this.code = code;
        this.result = result;
        this.message = message;
    }

    public static <T> ServerResponse<T> success() {
        return new ServerResponse<>(1, "success");
    }

    public static <T> ServerResponse<T> success(T result) {
        return ServerResponse.success(1, result, "success");
    }

    public static <T> ServerResponse<T> success(int code, T result, String message) {
        return new ServerResponse<>(1, result, "success");
    }

    public static <T> ServerResponse<PageResult<T>> success(List<T> data, long total, long page, long pageSize) {
        PageResult<T> pageResult = new PageResult<>(data, total, page, pageSize);
        return ServerResponse.success(pageResult);
    }

    public static <T> ServerResponse<T> fail() {
        return ServerResponse.fail(-1, "fail");
    }

    public static <T> ServerResponse<T> fail(String message) {
        return ServerResponse.fail(-1, message);
    }

    public static <T> ServerResponse<T> fail(int code, String message) {
        return ServerResponse.fail(code, null, message);
    }

    public static <T> ServerResponse<T> fail(int code, T result, String message) {
        return new ServerResponse<>(code, result, message);
    }

    public static <T> ServerResponse<T> fail(CommonError commonError) {
        return ServerResponse.fail(commonError.getCode(), commonError.getMessage());
    }

    public static <T> ServerResponse<T> fail(ExamProException exception) {
        if (exception.getCode() != 0)
            return ServerResponse.fail(exception.getCode(), exception.getMessage());
        return ServerResponse.fail(exception.getMessage());
    }
}